import { useState, useEffect, useRef } from "react";
import useSyncState from "@/hooks/useSyncState";
import { FileItemModel } from "@/api/interface/index";
import {
	goodsSkuGetSkuList,
	goodsSkuTypeDeleteSkuType,
	goodsSkuTypeModifySkuType,
	GoodsSkuGetSkuListItemModel
} from "@/api/modules/goodsSku";
import { myGoodsDetail, myGoodsList, myGoodsModify, GoodsItemModel, MyGoodsListSendModel } from "@/api/modules/goods";
import { setSku_list, setSpec_list, SkuListItem, SpecListItem } from "@/views/goods/set_Sku_data";
import { CategoryGetReturnItemModel, categoryGetTwo } from "@/api/modules/category";
import { Alert, Button, Checkbox, Form, Input, message, Modal, Popconfirm, Space, Table, Tag, Tooltip } from "antd";
import type { CheckboxValueType } from "antd/es/checkbox/Group";
import { CloseOutlined, FormOutlined, PlusOutlined, SearchOutlined } from "@ant-design/icons";
import dayjs from "dayjs";
import Cimage from "@/components/Cimage";
import CuploadImage, { CuploadImageMethods } from "@/components/CuploadImage";
import { showFullScreenLoading, tryHideFullScreenLoading } from "@/config/serviceLoading";

interface GoodsItemTableModel extends GoodsItemModel {
	sku_list?: SkuListItem[];
	spec_list?: SpecListItem[];
}
const goodsSkuSku = () => {
	/** 初始化数据 */
	const [loading, setLoading] = useState<boolean>(false);
	const [tableData, setTableData] = useState<GoodsItemTableModel[]>([]);
	const [listQuery, setListQuery, getListQuery] = useSyncState<MyGoodsListSendModel>({
		page: 1,
		size: 10,
		total: 0
	});
	async function getList() {
		setLoading(true);
		try {
			const { code, data } = await myGoodsList(getListQuery());
			if (code === 0) {
				const newTableData: GoodsItemTableModel[] = data.list || [];
				setListQuery({
					...getListQuery(),
					total: data.total
				});

				let flag = 0;
				for (let i = 0; i < newTableData.length; i++) {
					myGoodsDetail({ goodsId: newTableData[i].id }).then(({ code, data }) => {
						if (code === 0) {
							newTableData[i] = data;
							newTableData[i].sku_list = setSku_list(data, data.none_sku ? "none" : "");
							newTableData[i].spec_list = setSpec_list(data.skuList, data.none_sku ? "none" : "");
							flag++;
							if (flag === newTableData.length) {
								setLoading(false);
								console.log(newTableData, "商品数据");
								setTableData(newTableData || []);
							}
						}
					});
				}
			}
		} catch (error) {
			setLoading(false);
		}
	}
	interface SkuOption {
		label: string;
		value: string;
		disabled?: boolean;
	}
	// 获取sku大类一级分类
	const [skuList, setSkuList, getSkuList] = useSyncState<SkuOption[]>([]);
	async function getGoodsSku() {
		const { code, data } = await goodsSkuGetSkuList({ page: 1, size: 999 });
		if (code === 0)
			setSkuList(
				data.list.map(item => ({
					label: item.k,
					value: item.k_s || "",
					disabled: false
				}))
			);
	}
	// 表格分类回显文字部分
	const [categoryTwoData, setCategoryTwoData, getCategoryTwoData] = useSyncState<CategoryGetReturnItemModel[]>([]);
	async function getCategoryTwo() {
		// 获取二级分类
		const { data, code } = await categoryGetTwo();
		if (code === 0) setCategoryTwoData(data);
	}
	function categoryFilter(parentId: number | string) {
		const categoryTwoDataRef = getCategoryTwoData();
		if (categoryTwoDataRef?.length === 0) return "空";
		let categoryName = "";
		categoryTwoDataRef?.forEach(item => {
			if (item.id === parentId) categoryName = item.name;
		});
		return categoryName;
	}
	// 分页器变化回调
	function handleTableChange(pagination: any) {
		const listQueryRef: MyGoodsListSendModel = {
			page: pagination.current,
			size: pagination.pageSize,
			total: pagination.total
		};
		setListQuery(listQueryRef);
		getList();
	}
	/** 对话框 */
	interface Dialog {
		visible: boolean;
		title: string;
		pageType: string;
		skuGroupValue: Array<string>;
		goodsId: string | number;
		skuId?: number | null; // sku大类id
		skuItemId?: number | null; // sku小类id
		name?: string; // 小类规格名称
		imgId?: string; // 规格预览图片 id
		imgList?: FileItemModel[]; // 文件数据
		largeImageMode?: boolean;
	}
	const [dialog, setDialog] = useState<Dialog>({
		visible: false,
		title: "",
		pageType: "", // 对话框类型

		skuGroupValue: [], // sku一级分类复选框组value值
		goodsId: "", // 商品id

		skuId: null, // sku大类id
		skuItemId: null, // sku小类id
		name: "", // 小类规格名称
		imgId: "", // 规格预览图片 id
		imgList: [] // 文件数据
	});
	const [form] = Form.useForm();
	const [dialogLoading, setDialogLoading] = useState<boolean>(false);
	const imgIdRef = useRef<CuploadImageMethods>(null);
	// 是否正在上传或存在上传失败的文件
	const [uploadLoading, setUploadLoading] = useState<boolean>(false);
	interface OpenDialog {
		title?: string;
		goodsId: number;
		skuId?: number | null; // sku大类id
		skuItemId?: number | null; // sku小类id
		name?: string; // 小类规格名称
		imgId?: string; // 规格预览图片 id
		imgList?: FileItemModel[]; // 文件数据
		sku?: string;
		largeImageMode?: boolean;
	}
	function openDialog(pageType: string, data: OpenDialog) {
		// 打开对话框
		const newDialog: Dialog = {
			...dialog
		};
		newDialog.pageType = pageType;
		newDialog.visible = true;
		console.log(data, "data");
		switch (pageType) {
			case "skuSelect":
				newDialog.skuGroupValue = data.sku!.split(",").filter(item => item);
				newDialog.goodsId = data.goodsId;
				newDialog.title = "编辑Sku分类";
				break;
			case "addSku":
				newDialog.goodsId = data.goodsId;
				newDialog.title = `添加规格 - ${data.title}`;
				newDialog.skuId = data.skuId;
				newDialog.largeImageMode = data.largeImageMode;
				break;
			case "modefiSku":
				newDialog.skuId = data.skuId;
				newDialog.goodsId = data.goodsId;
				newDialog.title = `修改规格 - ${data.title} - ${data.name}`;
				newDialog.skuItemId = data.skuItemId;
				newDialog.imgId = data.imgId;
				newDialog.name = data.name;
				newDialog.imgList = data.imgList;
				newDialog.largeImageMode = data.largeImageMode;

				// 修改的时候回显数据
				form.setFieldsValue({ name: data.name, imgId: data.imgId?.split(",") });
				break;
		}
		setDialog(newDialog);
	}
	function closeDialog() {
		// 关闭对话框
		const newDialog = {
			visible: false,
			title: "",
			pageType: "", // 对话框类型

			skuGroupValue: [], // sku一级分类复选框组value值
			goodsId: "", // 商品id

			skuId: null, // sku大类id
			skuItemId: null, // sku小类id
			name: "", // 小类规格名称
			imgId: "", // 规格预览图片 id
			imgList: [] // 文件数据
		};
		form.resetFields();
		// 清空文件列表
		imgIdRef.current && imgIdRef.current.clearFileList();
		setDialog(newDialog);
	}
	// 点击确定按钮
	const handleDialogOk = () => {
		// form.submit();
		if (dialog.pageType === "skuSelect") {
			if (dialog.skuGroupValue.length === 0) {
				message?.warning("请至少选择一个Sku分类");
				return;
			}
			goodsModefy();
		} else if (dialog.pageType === "addSku" || dialog.pageType === "modefiSku") {
			if (uploadLoading) {
				message.warning("存在上传未完成或失败的图片，请检查后再提交！");
				return;
			}
			form.submit();
		}
	};
	// 提交修改sku分类接口
	async function goodsModefy() {
		setDialogLoading(true);
		try {
			// 修改商品sku
			const { code, msg } = await myGoodsModify({
				id: dialog.goodsId,
				sku: dialog.skuGroupValue?.toString(),
				none_sku: dialog.skuGroupValue?.length === 0
			});
			if (code === 0) {
				message?.success(msg);
				closeDialog();
				getList();
			}
		} finally {
			setDialogLoading(false);
		}
	}
	// 编辑sku分类回调
	function onSkuSelectChange(checkedValue: CheckboxValueType[]) {
		setDialog({
			...dialog,
			skuGroupValue: checkedValue as string[]
		});
	}
	// 提交新增/修改sku规格表单
	const onDialogFinish = async (form: any) => {
		console.log("form", dialog, form);
		const { code, msg } = await goodsSkuTypeModifySkuType({
			skuId: dialog.skuId as number,
			goodsId: dialog.goodsId as number,
			name: form.name as string,
			id: dialog.skuItemId ? dialog.skuItemId : undefined,
			imgId: form.imgId ? form.imgId.toString() : undefined
		});
		if (code === 0) {
			message?.success(msg);
			closeDialog();
			getList();
		}
	};
	// 修改sku规格表单失败回调
	const onDialogFinishFailed = (errorInfo: any) => {
		message.warning("请检查表单填写是否正确！");
		console.log("Failed:", errorInfo);
	};
	// 删除小类sku
	async function handleTagClose(id: number) {
		showFullScreenLoading();
		try {
			const { code, msg } = await goodsSkuTypeDeleteSkuType({ id });
			if (code === 0) {
				message?.success(msg);
				getList();
			}
		} finally {
			tryHideFullScreenLoading();
		}
	}
	// 文件上传状态回调
	function onStatusChange(status: string) {
		console.log(status, "status");
		setUploadLoading(status === "success" ? false : true);
	}
	// 文件上传回调
	function onChangeFormIds(name: string, ids: string[]) {
		console.log(name, ids);
		setDialog({ ...dialog, [name]: ids.toString() });
		form.setFieldValue(name, ids);
		form.validateFields([name]); // 触发表单验证
	}
	useEffect(() => {
		getGoodsSku();
		getCategoryTwo();
		getList();
	}, []);
	function expandedRowRenderItem(record: GoodsItemTableModel) {
		return (
			<>
				{record.spec_list?.map((value: SpecListItem, idx: number) => (
					<div className="flex items-center pb-10 ml-20 pt-10" key={idx}>
						<span>{value.name}</span>
						{value.list.map(v => (
							<div key={v.id} className="flex items-center ml-20">
								{v.imgUrl && <Cimage width={35} height={35} src={v.imgUrl[0].url} />}
								<Tag color="default" className="!text-14 !p-[7px_10px]">
									<span style={{ color: "#909399" }}>{v.name}</span>
									<FormOutlined
										className="cursor-pointer ml-10"
										onClick={() =>
											openDialog("modefiSku", {
												title: value.name,
												name: v.name,
												skuId: v.skuId,
												skuItemId: v.id,
												imgId: v.imgUrl ? v.imgUrl[0].id.toString() : "",
												imgList: v.imgUrl || [],
												goodsId: record.id,
												largeImageMode: value.largeImageMode
											})
										}
									/>
									<Popconfirm
										title="确定执行该操作吗？"
										className="ml-10"
										onConfirm={() => handleTagClose(v.id)}
										okText="Yes"
										cancelText="No"
									>
										<CloseOutlined className="cursor-pointer" />
									</Popconfirm>
								</Tag>
							</div>
						))}
						<Button
							type="primary"
							icon={<PlusOutlined />}
							className="ml-10"
							onClick={() =>
								openDialog("addSku", {
									title: value.name,
									skuId: Number(value.skuId),
									goodsId: record.id,
									largeImageMode: value.largeImageMode
								})
							}
						>
							添加
						</Button>
					</div>
				))}
			</>
		);
	}
	const columns: any[] = [
		{
			title: "上架时间",
			dataIndex: "createTime",
			key: "createTime",
			align: "center",
			ellipsis: {
				showTitle: false
			},
			width: "15%",
			render: (createTime: number) => (
				<Tooltip placement="topLeft" title={dayjs(createTime || new Date()).format("YYYY-MM-DD HH:mm")}>
					{dayjs(createTime || new Date()).format("YYYY-MM-DD HH:mm")}
				</Tooltip>
			)
		},
		{
			title: "商品封面",
			dataIndex: "iconId",
			key: "iconId",
			align: "center",
			ellipsis: {
				showTitle: false
			},
			width: "10%",
			className: "iconId_tableClass",
			render: (_: any, record: GoodsItemTableModel) => <Cimage src={record.iconId[0].url} width={80} height={80}></Cimage>
		},
		{
			title: "商品名称",
			dataIndex: "name",
			key: "name",
			align: "center",
			width: "20%"
		},
		{
			title: "商品标签",
			dataIndex: "hot",
			key: "hot",
			align: "center",
			width: "10%",
			render: (_: any, record: GoodsItemTableModel) => <Tag color="green">{record.hot}</Tag>
		},
		{
			title: "商品类别",
			dataIndex: "parentId",
			key: "parentId",
			align: "center",
			width: "10%",
			render: (_: any, record: GoodsItemTableModel) => <>{categoryFilter(record.parentId)}</>
		},
		{
			title: "商品库存",
			dataIndex: "stock_num",
			key: "stock_num",
			align: "center",
			width: "10%"
		},
		{
			title: "规格信息",
			dataIndex: "none_sku",
			key: "none_sku",
			align: "center",
			width: "10%",
			render: (_: any, record: GoodsItemTableModel) => (
				<Tag color={record.none_sku ? "red" : "blue"}>{record.none_sku ? "无规格商品" : "多个规格商品"}</Tag>
			)
		},
		{
			title: "操作",
			align: "center",
			key: "action",
			width: "15%",
			render: (_: any, record: GoodsItemTableModel) => (
				<Space wrap>
					<Button
						type="primary"
						disabled={record.none_sku ? true : false}
						icon={<FormOutlined />}
						onClick={e => {
							e.stopPropagation();
							openDialog("skuSelect", { goodsId: record.id, sku: record.sku });
						}}
					>
						编辑Sku分类
					</Button>
				</Space>
			)
		}
	];
	return (
		<div className="goodsSkuSku">
			<div className="goodsSkuList__title flex items-center justify-between mb-10">
				<Space className="flex items-center" size="large">
					<span className="text-18 font-bold">Sku列表</span>
				</Space>
				<Space className="flex items-center">
					<Button
						type="primary"
						icon={<SearchOutlined />}
						onClick={() => {
							getList();
						}}
					>
						查询
					</Button>
				</Space>
			</div>
			<div className="goodsSkuList__content">
				<Table
					loading={loading}
					bordered={false}
					dataSource={tableData}
					columns={columns}
					rowKey={record => record.id}
					scroll={{ x: true }}
					pagination={{
						current: listQuery.page, // 当前页码
						pageSize: listQuery.size, // 每页条数
						total: listQuery.total, // 数据总数
						showSizeChanger: true, // 显示每页条数切换器
						showQuickJumper: true // 显示快速跳转输入框
					}}
					expandable={{
						expandedRowRender: expandedRowRenderItem,
						rowExpandable: record => !record.none_sku,
						expandRowByClick: true
					}}
					onChange={pagination => handleTableChange(pagination)} // 分页变化回调
				/>
			</div>
			{/* 添加sku规格弹窗 */}
			<Modal
				width={600}
				title={dialog.title}
				open={dialog.visible}
				destroyOnClose={true}
				onOk={handleDialogOk}
				confirmLoading={dialogLoading}
				onCancel={closeDialog}
			>
				{dialog.pageType === "skuSelect" && (
					<Checkbox.Group options={skuList} value={dialog.skuGroupValue} onChange={onSkuSelectChange} />
				)}
				{(dialog.pageType === "addSku" || dialog.pageType === "modefiSku") && (
					<Form
						form={form}
						preserve={false}
						size="middle"
						autoComplete="off"
						onFinish={onDialogFinish}
						onFinishFailed={onDialogFinishFailed}
					>
						<Alert message="请在显示大图的分类中上传传规格封面" type="warning" showIcon closable className="!mb-10" />
						{dialog.largeImageMode && (
							<Form.Item label="规格封面" name="imgId" rules={[{ required: true, message: "请上传规格封面" }]}>
								<CuploadImage
									ref={imgIdRef}
									max={1}
									defaultFileList={dialog.imgList}
									onStatusChange={onStatusChange}
									onChangeIds={ids => onChangeFormIds("imgId", ids)}
								/>
							</Form.Item>
						)}
						<Form.Item label="规格名称" name="name" rules={[{ required: true, message: "请输入规格名称" }]}>
							<Input placeholder="输入规格名称" maxLength={200} showCount />
						</Form.Item>
					</Form>
				)}
			</Modal>
		</div>
	);
};
export default goodsSkuSku;
